<!-- templates/ef_devices.html -->
{% extends "base.html" %}

{% block title %}电子围栏设备管理 - 告警系统{% endblock %}

{% block content %}
<div class="d-flex justify-content-between align-items-center mb-4">
    <div>
        <h2 class="mb-1"><i class="bi bi-camera-video me-2"></i>电子围栏设备管理</h2>
        <p class="text-muted mb-0">管理您的电子围栏</p>
    </div>
    <div>
        <button class="btn btn-outline-secondary" onclick="location.reload()">
            <i class="bi bi-arrow-clockwise"></i> 刷新
        </button>
    </div>
</div>

{% if fences and fences|length > 0 %}
    <div class="card shadow-sm">
        <div class="table-responsive">
            <table class="table table-hover mb-0">
                <thead class="bg-primary text-white">
                    <tr>
                        <th>序号</th>
                        <th>设备名称</th>
                        <th>设备描述</th>
                        <th class="text-center">状态</th>  <!-- 添加 text-center 类 -->
                        <!-- <th class="text-center">电量</th>  添加 text-center 类 -->
                        <th>区域</th>
                        <th class="text-center">操作</th>
                    </tr>
                </thead>
                <tbody id="fenceTableBody">
                    {% for fence in fences %}
                    <tr>
                        <td class="fw-medium">{{ loop.index }}</td>
                        <td class="fw-medium">{{ fence.FenceName }}</td>
                        <td class="fence-desc" data-id="{{ fence.FenceId }}">{{ fence.FenceDesc }}</td>
                        <td class="text-center">  <!-- 添加 text-center 类 -->
                            {% if fence.FenceState == 'o' %}
                            <span class="badge bg-success">布防</span>
                            {% elif fence.FenceState == 'c' %}
                            <span class="badge bg-danger">撤防</span>
                            {% else %}
                            <span class="badge bg-danger">离线</span>
                            {% endif %}
                        </td>
                        <!-- <td class="text-center">{{ fence.Electricity }}%</td>  修复电量显示 -->
                        <td>  <!-- 新增区域列 -->
                            <div class="d-flex align-items-center">
                                <div class="text-truncate" style="max-width: 100px;" 
                                    title="{{ fence.AreaName or '未设置区域' }}">
                                    {{ fence.AreaName or '-' }}
                                </div>
                                <button class="btn btn-sm btn-link p-0 ms-2 edit-area-btn"
                                        data-id="{{ fence.FenceId }}"
                                        data-current-area="{{ fence.AreaId }}"
                                        title="编辑区域">
                                    <i class="bi bi-pencil"></i>
                                </button>
                            </div>
                        </td>
                        <td class="text-center">
                            <div class="d-flex justify-content-center">  <!-- 添加包裹容器 -->
                                <button class="btn btn-sm btn-warning edit-btn" data-id="{{ fence.FenceId }}" data-bs-toggle="modal" data-bs-target="#editDeviceModal">
                                    <i class="bi bi-pencil"></i>
                                </button>
                                <button class="btn btn-sm btn-danger delete-btn ms-2" data-id="{{ fence.FenceId }}">
                                    <i class="bi bi-trash"></i>
                                </button>
                            </div>
                        </td>
                    </tr>
                    {% endfor %}
                </tbody>
            </table>
        </div>
    </div>
{% else %}
    <div class="d-flex justify-content-center align-items-center" style="min-height: 400px;">
        <div class="alert alert-primary text-center p-5 rounded-3">
            <div class="mb-3">
                <i class="bi bi-info-circle fs-1 text-primary"></i>
            </div>
            <h4 class="fw-bold">暂无设备数据</h4>
            <p class="mt-2 text-muted">系统中没有记录的电子围栏设备信息。</p>
        </div>
    </div>
{% endif %}

<!-- 添加编辑区域模态框 -->
<div class="modal fade" id="editAreaModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header bg-primary text-white">
                <h5 class="modal-title"><i class="bi bi-pencil me-2"></i>编辑区域</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form id="editAreaForm">
                <div class="modal-body">
                    <input type="hidden" id="editAreaFenceId" name="fence_id">
                    <div class="mb-3">
                        <label class="form-label">选择区域 <span class="text-danger">*</span></label>
                        <select class="form-select" id="editAreaId" name="area_id" required>
                            <option value="">-- 选择区域 --</option>
                            {% for area in areas %}
                                <option value="{{ area.AreaId }}">{{ area.AreaName }}</option>
                            {% endfor %}
                        </select>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="submit" class="btn btn-primary">保存</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- 编辑设备模态框 -->
<div class="modal fade" id="editDeviceModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">编辑设备信息</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="editDeviceForm">
                    <input type="hidden" id="editDeviceId" name="device_id">
                    <div class="mb-3">
                        <label class="form-label">设备名称</label>
                        <input type="text" class="form-control" id="editDeviceName" disabled>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">设备描述</label>
                        <textarea class="form-control" id="editDeviceDesc" name="device_desc" rows="3" required></textarea>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" id="updateDeviceBtn">更新</button>
            </div>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // 设置定时刷新，每5秒执行一次
    const refreshInterval = setInterval(fetchFenceStatus, 5000);
    
    // 首次加载时立即执行一次
    fetchFenceStatus();
    
    // 刷新函数
    async function fetchFenceStatus() {
        try {
            const response = await fetch('/api/fence/devices');
            const data = await response.json();
            
            if (data.status === 'success') {
                updateFenceTable(data.fences);
            }
        } catch (error) {
            console.error('获取设备状态失败:', error);
        }
    } 
    
    // 更新表格内容
    function updateFenceTable(fences) {
        const tbody = document.getElementById('fenceTableBody');
        if (!tbody) return;
        
        if (!fences || fences.length === 0) {
            tbody.innerHTML = `
                <tr>
                    <td colspan="7" class="text-center py-5">  <!-- 修正 colspan 为 7 -->
                        <div class="alert alert-info mb-0">暂无设备数据</div>
                    </td>
                </tr>
            `;
            return;
        }
        
        // 重新渲染表格行
        tbody.innerHTML = '';
        
        fences.forEach((fence, index) => {
            // 使用序号代替设备ID
            const rowIndex = index + 1;
            
            // 修复状态显示逻辑
            let stateBadge;
            if (fence.FenceState === 'o') {
                stateBadge = '<span class="badge bg-success">布防</span>';
            } else if (fence.FenceState === 'c') {
                stateBadge = '<span class="badge bg-danger">撤防</span>';
            } else {
                stateBadge = '<span class="badge bg-danger">离线</span>';
            }
            
            // 添加区域列
            const areaCell = `
                <td>
                    <div class="d-flex align-items-center">
                        <div class="text-truncate" style="max-width: 100px;" 
                            title="${fence.AreaName || '未设置区域'}">
                            ${fence.AreaName || '-'}
                        </div>
                        <button class="btn btn-sm btn-link p-0 ms-2 edit-area-btn"
                                data-id="${fence.FenceId}"
                                data-current-area="${fence.AreaId || ''}"
                                title="编辑区域">
                            <i class="bi bi-pencil"></i>
                        </button>
                    </div>
                </td>
            `;
            
            const tr = document.createElement('tr');
            tr.innerHTML = `
                <td class="fw-medium">${rowIndex}</td>
                <td class="fw-medium">${fence.FenceName}</td>
                <td class="fence-desc" data-id="${fence.FenceId}">${fence.FenceDesc || '-'}</td>
                <td class="text-center">${stateBadge}</td>
                ${areaCell}  <!-- 添加区域列 -->
                <td class="text-center">
                    <div class="d-flex justify-content-center">
                        <button class="btn btn-sm btn-warning edit-btn" data-id="${fence.FenceId}" data-bs-toggle="modal" data-bs-target="#editDeviceModal">
                            <i class="bi bi-pencil"></i>
                        </button>
                        <button class="btn btn-sm btn-danger delete-btn ms-2" data-id="${fence.FenceId}">
                            <i class="bi bi-trash"></i>
                        </button>
                    </div>
                </td>
            `;
            tbody.appendChild(tr);
        });
        
        // 重新绑定事件
        bindEditButtons();
        bindDeleteButtons();
        bindEditAreaButtons();  // 绑定区域编辑按钮
    }
        // 编辑区域表单提交
    document.getElementById('editAreaForm').addEventListener('submit', function(e) {
        e.preventDefault();
        
        const fenceId = document.getElementById('editAreaFenceId').value;
        const areaId = document.getElementById('editAreaId').value;
        
        fetch('/api/fence/update-area', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: `fence_id=${fenceId}&area_id=${areaId}`
        })
        .then(response => response.json())
        .then(data => {
            if (data.status === 'success') {
                alert('区域更新成功');
                bootstrap.Modal.getInstance(document.getElementById('editAreaModal')).hide();
                
                // 更新UI
                const areaName = document.querySelector(`#editAreaId option[value="${areaId}"]`).text;
                const row = document.querySelector(`.edit-area-btn[data-id="${fenceId}"]`).closest('tr');
                row.querySelector('.text-truncate').textContent = areaName;
                row.querySelector('.text-truncate').title = areaName;
            } else {
                alert('更新失败: ' + data.message);
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('请求失败: ' + error.message);
        });
    });
    
    // 初始化绑定
    bindEditAreaButtons();

    function bindEditAreaButtons() {
        document.querySelectorAll('.edit-area-btn').forEach(btn => {
            btn.addEventListener('click', function() {
                const fenceId = this.getAttribute('data-id');
                const currentAreaId = this.getAttribute('data-current-area');
                
                document.getElementById('editAreaFenceId').value = fenceId;
                document.getElementById('editAreaId').value = currentAreaId || '';
                
                const modal = new bootstrap.Modal(document.getElementById('editAreaModal'));
                modal.show();
            });
        });
    }
    
    // 绑定编辑按钮事件
    function bindEditButtons() {
        document.querySelectorAll('.edit-btn').forEach(btn => {
            btn.addEventListener('click', function() {
                const deviceId = this.getAttribute('data-id');
                const deviceName = this.closest('tr').querySelector('td:nth-child(2)').textContent;
                const deviceDesc = this.closest('tr').querySelector('.fence-desc').textContent;
                
                document.getElementById('editDeviceId').value = deviceId;
                document.getElementById('editDeviceName').value = deviceName;
                document.getElementById('editDeviceDesc').value = deviceDesc;
            });
        });
    }
    
    // 绑定删除按钮事件
    function bindDeleteButtons() {
        document.querySelectorAll('.delete-btn').forEach(btn => {
            btn.addEventListener('click', function() {
                const deviceId = this.getAttribute('data-id');
                if (confirm('确定要删除这个设备吗？')) {
                    deleteDevice(deviceId);
                }
            });
        });
    }
    
    // 更新设备信息
    document.getElementById('updateDeviceBtn').addEventListener('click', async function() {
        const deviceId = document.getElementById('editDeviceId').value;
        const deviceDesc = document.getElementById('editDeviceDesc').value;
        
        if (!deviceDesc) {
            alert('设备描述不能为空');
            return;
        }
        
        try {
            const response = await fetch('/api/fence/update', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: `fence_id=${deviceId}&fence_desc=${encodeURIComponent(deviceDesc)}`
            });
            
            const result = await response.json();
            
            if (result.status === 'success') {
                alert('设备信息更新成功');
                document.querySelector(`.fence-desc[data-id="${deviceId}"]`).textContent = deviceDesc;
                $('#editDeviceModal').modal('hide');
            } else {
                alert('更新失败: ' + (result.message || '未知错误'));
            }
        } catch (error) {
            console.error('更新失败:', error);
            alert('更新失败，请检查网络连接');
        }
    });
    
    // 删除设备（逻辑删除）
    async function deleteDevice(deviceId) {
        try {
            const response = await fetch(`/api/fence/delete?fence_id=${deviceId}`, {
                method: 'DELETE'
            });
            
            const result = await response.json();
            
            if (result.status === 'success') {
                alert('设备删除成功');
                fetchFenceStatus();
            } else {
                alert('删除失败: ' + (result.message || '未知错误'));
            }
        } catch (error) {
            console.error('删除失败:', error);
            alert('删除失败，请检查网络连接');
        }
    }
    
    // 初始化绑定
    bindEditButtons();
    bindDeleteButtons();
});
</script>
{% endblock %}